const db = require("../models");
const logger = require("../utils/utils.logger");
const DAO = require("../dao/DAO");
const {sendMailer} = require("../utils/utils.nodemailer");
const Msg = db.msg;
const ChatRoom = db.chatRoom;
const ChatHistory = db.chatHistory;
const {Op} = require("sequelize");

// 创建并保存新消息
exports.create = (req, res) => {
  const pm = req.body;
  // 请求验证
  // if (!pm.email) return res.sendResult({data: '', code: 605, message: "留言邮箱不能为空！"})
  if (!pm.content) return res.sendResult({data: '', code: 605, message: "留言内容不能为空！"})
  // 创建消息对象
  const newMessage = {
    username: pm.username || '',
    email: pm.email,
    receive: pm.receive || '',
    content: pm.content,
    isRoom: pm.isRoom|| 0,
    roomname: pm.roomName || '',
    roomId: pm.roomId || '',
  };
  DAO.create(Msg, newMessage, data => {
    res.sendResult(data)
    // 留言成功后可以发送邮件通知
    // let p = {
    //     email: '接收邮箱',
    //     content: `您收到了一份留言：${pm.content},-----快去查看`
    // }
    // sendMailer(p).then(info => {
    //     console.log('邮件发送成功');
    // })
  })
};

// 获取所有消息
exports.findAll = (req, res) => {
  const pm = req.query || req.body;

  // 确保有排序参数，默认按创建时间升序排列（旧消息在前）
  if (!pm.order) {
    pm.order = [['createdAt', 'DESC']];
  }

  // 设置默认限制为1000条记录
  if (!pm.limit) {
    pm.limit = 1000;
  }

  DAO.list(Msg, pm, list => {
    res.sendResult(list)
  })
};

// 根据ID查找单个消息
exports.findOne = (req, res) => {
  const pm = req.body;
  DAO.findOne(Msg, pm, data => {
    res.sendResult(data)
  })
};

// 更新消息
exports.update = (req, res) => {
  const pm = req.body;
  // 请求验证
  if (!pm.id) return res.sendResult({data: '', code: 605, message: "ID不能为空！"})
  DAO.update(Msg, pm, {id: pm.id}, data => {
    logger.debug(`${req.method} ${req.baseUrl + req.path} *** 参数：${JSON.stringify(pm)}; 响应：${JSON.stringify(data)}`);
    res.sendResult(data)
  })
};

// 删除消息
exports.delete = (req, res) => {
  const pm = req.body;
  // 请求验证
  if (!pm.id) return res.sendResult({data: '', code: 605, message: "ID不能为空！"})
  DAO.delete(Msg, {id: pm.id}, data => {
    logger.debug(`${req.method} ${req.baseUrl + req.path} *** 参数：${JSON.stringify(pm)}; 响应：${JSON.stringify(data)}`);
    res.sendResult(data)
  })
};

// 回复消息
exports.replyMsg = (req, res) => {
  const pm = req.body;
  // 验证参数
  if (!pm.id) return res.sendResult({data: '', code: 605, message: "ID不能为空！"})
  if (!pm.content) return res.sendResult({data: '', code: 605, message: "回复内容不能为空！"})

  // 更新消息状态
  Msg.update({status: true}, {
    where: {
      id: pm.id
    }
  }).then(_info => {
    res.status(200).sendResultAto(_info, 200, '回复成功！')

    // 可以在这里添加邮件回复功能
    // if (pm.email) {
    //     sendMailer({email: pm.email, content: pm.content}).then(info => {
    //         console.log('回复邮件发送成功');
    //     }).catch(err => {
    //         console.log("邮件发送错误:", err);
    //     });
    // }
  }).catch(err => {
    console.log("err:", err)
    res.status(500).sendResultAto(err, 605, '回复失败！')
  })
};

// 新增：获取聊天记录
exports.getChatHistory = (req, res) => {
  const pm = req.query || req.body;
  const username = pm.username;

  if (!username) {
    return res.sendResult({data: '', code: 605, message: "用户名不能为空！"});
  }

  // 查询与当前用户相关的所有聊天记录
  Msg.findAll({
    where: {
      [Op.or]: [
        {username: username},
        {receive: username}
      ]
    },
    order: [['createdAt', 'ASC']] // 按时间升序排序

  }).then(messages => {
    // 处理聊天历史记录，获取聊天过的用户列表
    const chatUsers = new Set();
    const userLastMsg = {};

    messages.forEach(msg => {
      const msgData = msg.dataValues;
      // 确定聊天对象
      let chatUser = '';
      if (msgData.username === username) {
        chatUser = msgData.receive;
      } else {
        chatUser = msgData.username;
      }

      if (chatUser) {
        chatUsers.add(chatUser);
        // 记录最后一条消息时间
        userLastMsg[chatUser] = {
          username: chatUser,
          lastTime: msgData.createdAt
        };
      }
    });

    // 转换为数组格式
    const result = Array.from(chatUsers).map(user => userLastMsg[user]);

    res.sendResult({
      data: result,
      code: 200,
      message: "获取聊天历史成功"
    });
  }).catch(err => {
    console.error("获取聊天历史错误:", err);
    res.sendResult({
      data: '',
      code: 500,
      message: "获取聊天历史失败"
    });
  });
};

// 新增：获取与特定用户的聊天记录
// 新增：获取与特定用户的聊天记录
exports.getChatMessages = (req, res) => {
  const pm = req.query || req.body;
  const currentUser = pm.username;
  const targetUser = pm.receive;

  if (!currentUser || !targetUser) {
    return res.sendResult({data: '', code: 605, message: "用户名和目标用户不能为空！"});
  }

  // 查询与目标用户的聊天记录
  Msg.findAll({
    where: {
      [Op.or]: [
        {username: currentUser, receive: targetUser},
        {username: targetUser, receive: currentUser}
      ]
    },
    order: [['createdAt', 'ASC']], // 按时间升序排序，旧消息在前
  }).then(messages => {
    res.sendResult({
      data: messages,
      code: 200,
      message: "获取聊天记录成功"
    });
  }).catch(err => {
    console.error("获取聊天记录错误:", err);
    res.sendResult({
      data: '',
      code: 500,
      message: "获取聊天记录失败"
    });
  });
};

// 创建聊天室
exports.createChatRoom = async (req, res) => {
  try {
    const {roomName, roomId, creator, members} = req.body;

    // 检查房间ID是否已存在
    const existingRoom = await ChatRoom.findOne({where: {roomId}});
    if (existingRoom) {
      return res.json({
        meta: {
          status: 400,
          message: '该群聊ID已存在，请更换一个'
        }
      });
    }

    // 创建聊天室
    const chatRoom = await ChatRoom.create({
      roomName,
      roomId,
      creator,
      members: JSON.stringify(members),
      createdAt: new Date()
    });

    // 添加到聊天历史
    await ChatHistory.create({
      username: roomName,
      roomId,
      isRoom: true,
      lastTime: new Date()
    });

    return res.json({
      meta: {
        status: 200,
        message: '创建群聊成功'
      },
      data: chatRoom
    });
  } catch (error) {
    console.error('创建群聊异常:', error);
    return res.json({
      meta: {
        status: 500,
        message: '服务器异常'
      }
    });
  }
};

// 加入聊天室
exports.joinChatRoom = async (req, res) => {
  try {
    const {roomId, username} = req.body;

    // 查找聊天室
    const chatRoom = await ChatRoom.findOne({where: {roomId}});
    if (!chatRoom) {
      return res.json({
        meta: {
          status: 404,
          message: '群聊不存在'
        }
      });
    }

    // 检查用户是否已在群聊中
    const members = JSON.parse(chatRoom.members || '[]');
    if (members.includes(username)) {
      return res.json({
        meta: {
          status: 400,
          message: '您已经在该群聊中'
        }
      });
    }

    // 添加用户到群聊
    members.push(username);
    await chatRoom.update({members: JSON.stringify(members)});

    // 添加到用户的聊天历史
    const existingHistory = await ChatHistory.findOne({
      where: {
        username: chatRoom.roomName,
        roomId
      }
    });

    if (!existingHistory) {
      await ChatHistory.create({
        username: chatRoom.roomName,
        roomId,
        isRoom: true,
        lastTime: new Date()
      });
    }

    return res.json({
      meta: {
        status: 200,
        message: '加入群聊成功'
      },
      data: chatRoom
    });
  } catch (error) {
    console.error('加入群聊异常:', error);
    return res.json({
      meta: {
        status: 500,
        message: '服务器异常'
      }
    });
  }
};

// 搜索聊天室
exports.searchChatRoom = async (req, res) => {
  try {
    const {roomId} = req.query;

    // 查找聊天室
    const chatRoom = await ChatRoom.findOne({where: {roomId}});
    if (!chatRoom) {
      return res.json({
        meta: {
          status: 404,
          message: '群聊不存在'
        }
      });
    }

    return res.json({
      meta: {
        status: 200,
        message: '查询群聊成功'
      },
      data: chatRoom
    });
  } catch (error) {
    console.error('查询群聊异常:', error);
    return res.json({
      meta: {
        status: 500,
        message: '服务器异常'
      }
    });
  }
};

// 获取聊天室信息
exports.getRoomInfo = async (req, res) => {
  try {
    const {username, roomId} = req.query;

    // 如果提供了roomId，查询特定聊天室信息
    if (roomId) {
      const chatRoom = await ChatRoom.findOne({where: {roomId}});
      if (!chatRoom) {
        return res.json({
          meta: {
            status: 404,
            message: '群聊不存在'
          }
        });
      }

      // 解析成员列表
      let members = [];
      try {
        members = JSON.parse(chatRoom.members || '[]');
      } catch (e) {
        console.error('解析群聊成员列表错误:', e);
      }

      // 返回聊天室信息，包括成员列表
      return res.json({
        meta: {
          status: 200,
          message: '获取群聊信息成功'
        },
        data: {
          ...chatRoom.dataValues,
          members
        }
      });
    }

    // 如果提供了username，查询用户加入的所有聊天室
    else if (username) {
      // 查找所有聊天室
      const allRooms = await ChatRoom.findAll();

      // 过滤出用户加入的聊天室
      const userRooms = allRooms.filter(room => {
        try {
          const members = JSON.parse(room.members || '[]');
          return members.includes(username);
        } catch (e) {
          console.error('解析群聊成员列表错误:', e);
          return false;
        }
      });

      return res.json({
        meta: {
          status: 200,
          message: '获取用户群聊列表成功'
        },
        data: userRooms
      });
    }

    // 如果既没有提供roomId也没有提供username，返回错误
    else {
      return res.json({
        meta: {
          status: 400,
          message: '请提供用户名或群聊ID'
        }
      });
    }
  } catch (error) {
    console.error('获取群聊信息异常:', error);
    return res.json({
      meta: {
        status: 500,
        message: '服务器异常'
      }
    });
  }
};

// 获取群聊消息
exports.getGroupMessages = async (req, res) => {
  try {
    const pm = req.body;
    const roomId = pm.where?.roomId;

    if (!roomId) {
      return res.json({
        meta: {
          status: 400,
          message: '群聊ID不能为空'
        }
      });
    }

    // 设置查询条件
    const queryOptions = {
      where: {
        roomId: roomId
      }
    };

    // 处理排序参数
    if (pm.order) {
      queryOptions.order = pm.order;
    } else {
      queryOptions.order = [['createdAt', 'ASC']]; // 默认按时间升序排序，旧消息在前
    }

    // 处理限制参数
    if (pm.limit) {
      queryOptions.limit = parseInt(pm.limit);
    }

    // 查询群聊消息
    const messages = await Msg.findAll(queryOptions);

    // 查询聊天室信息
    const chatRoom = await ChatRoom.findOne({
      where: {roomId}
    });

    if (!chatRoom) {
      return res.json({
        meta: {
          status: 404,
          message: '群聊不存在'
        }
      });
    }

    return res.json({
      meta: {
        status: 200,
        message: '获取群聊消息成功'
      },
      data: {
        roomInfo: chatRoom,
        data: messages
      }
    });
  } catch (error) {
    console.error('获取群聊消息异常:', error);
    return res.json({
      meta: {
        status: 500,
        message: '服务器异常'
      }
    });
  }
};
